<template>
    <div>
        <!-- 按钮容器 -->
        <div class="button-container">
            <input type="file" id="fileInput" @change="handleFileSelect" style="display: none;">
            <button @click="openFileSelector" class="select-photo">选择文件</button>
            <button @click="handleGrayScale" class="gray-preprocess">灰度化预处理</button>
        </div>
        <!-- 图片容器 -->
        <div class="image-container">
            <img v-if="imageUrl" :src="imageUrl" alt="Selected Image" class="selected-image">
            <img v-if="grayImageUrl" :src="grayImageUrl" alt="Gray Image" class="selected-image">
        </div>
    </div>
</template>

<script>
import axios from 'axios';

export default {
    data() {
        return {
            selectedFile: null,
            imageUrl: null,
            grayImageUrl: null
        };
    },
    methods: {
        openFileSelector() {
            document.getElementById('fileInput').click();
        },
        handleFileSelect(event) {
            const file = event.target.files[0];
            if (file) {
                this.selectedFile = file;
                const reader = new FileReader();
                reader.onload = (e) => {
                    this.imageUrl = e.target.result;
                };
                reader.readAsDataURL(file);
            }
        },
        async handleGrayScale() {
            if (!this.selectedFile) {
                alert('请先选择文件');
                return;
            }
            const formData = new FormData();
            formData.append('image', this.selectedFile);
            formData.append('fileName', this.selectedFile.name);
            try {
                const response = await axios.post('http://127.0.0.1:5000/api/gray_scale', formData);
                console.log('灰度化处理成功', response.data);
                const imageBase64 = response.data.imageBase64;
                this.grayImageUrl = `data:image/jpeg;base64,${imageBase64}`;
            } catch (error) {
                console.error('灰度化处理失败', error);
            }
        }
    }
};
</script>

<style scoped>
.select-photo {
    background-color: #28a745;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    font-size: 14px;
    margin-left: 10px;
}

.gray-preprocess {
    background-color: #48bdc1;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    font-size: 14px;
    margin-left: 10px;
}

.selected-image {
    max-width: 100%;
    max-height: 300px;
    width: auto;
    height: auto;
    object-fit: contain;
    margin: 0 100px;
}

.button-container {
    margin-bottom: 20px;
}

.image-container {
    text-align: left;
}
</style>